<template>
  <!-- 单体温度监控 -->
  <div class="tempChartContent">
    <a-spin :spinning="chartLoading">
      <div :key="index" id="temperature0" class="chartContainer" />
      <div :key="index" id="temperature1" class="chartContainer" />
      <div :key="index" id="temperature2" class="chartContainer" />
    </a-spin>
  </div>
</template>
<script setup>
;
import { commonConfigStore } from "@/stores/commonConfig";
import * as echarts from "echarts";
import { getTemperatureOption, diffOption } from "./chartOption";
import DetailsData from "./detailsData.vue";
import { getCurrentDate, getYesterdayFromDate } from "@/utils/common";
import { random, cloneDeep } from "lodash-es";

const props = defineProps({
  stationInfo: {
    type: [Number, Object],
  },
  externalParams: {
    type: Object,
    default: () => ({}),
  },
});

const emit = defineEmits(['loading-change']);
const energyLinkList = ref([]);

const form = ref({
  date: null,
  linkId: null,
  equipId: null,
});
const $api = inject("$api");
const chartType = ref(null);



const chartsData = ref([]);
const chartTypeList = ref([
  {
    value: 1,
    label: "电池簇",
  },
  {
    value: 2,
    label: "电池堆",
  },
  {
    value: 3,
    label: "电站",
  },
]);
const changeChartType = async () => {
  form.value.linkId = null;
  form.value.equipId = null;
  switch (chartType.value) {
    case 1:
      // 如果是电池簇
      form.value.linkId = energyLinkList.value[0].deviceId;
      await getBlockList(form.value.linkId);
      form.value.equipId = blockList.value?.[0]?.deviceId;
      break;
    case 2:
      // 如果是电池堆
      form.value.linkId = energyLinkList.value[0].deviceId;
  }
};
const getTempDimension = async () => {
  const res = await $api.temperatureDimension({
    stationId: props.stationInfo.id,
  });
  if (res?.code === 0) {
    chartTypeList.value = chartTypeList.value.filter((item) =>
      res.data.includes(item.value)
    );
    chartType.value = chartTypeList.value[0].value;
    await changeChartType(); // 处理维度、电池堆、电池簇联动
    getTempData();
  }
};
const getEnergyLinkList = async () => {
  // 获取电池堆列表 如果不是主电池堆，需要拉取电池堆列表指定所属
  const res = await $api.energyLinkList({
    current: 1,
    size: 10000,
    stationId: props.stationInfo.id,
  });
  energyLinkList.value = res?.data;
};
const blockList = ref([]);
const getBlockList = async (id) => {
  const params = {
    stationId: props.stationInfo.id,
    linkId: id,
  };
  const res = await $api.powerBlockList(params);
  if (res && res.code === 0) {
    blockList.value = res.data;
  }
};
const maxChartOptionData = ref({});
const minChartOptionData = ref({});
const diffChartOptionData = ref({});
const chartLoading = ref(false);

// 添加tooltipData用于存储位置信息
const maxTooltipData = ref({});
const minTooltipData = ref({});

// 监听loading状态变化并emit事件
watch(chartLoading, (newVal) => {
  emit('loading-change', newVal);
});
const maxChartSetup = ref(false);

// 构建tooltipData的辅助函数
const buildTooltipData = (chartData, tooltipDataRef) => {
  if (!chartData || !chartData.lineData) return;
  
  chartData.lineData.forEach(item => {
    if (!item.dateTime) return;
    
    const time = item.dateTime.substring(11, 16); // 提取HH:MM格式时间
    tooltipDataRef.value[time] = {
      linkName: chartData.linkName || '',
      blockName: chartData.blockName || '',
      value: item.value
    };
  });
};

const initMaxChart = async (chartData, lineType) => {
  // 1-最低温度 2-最高温度
  const xAxisData = chartData.lineData.map(
    (item) => item.dateTime.split(" ")[1]
  );
  
  // 构建tooltip数据
  buildTooltipData(chartData, maxTooltipData);
  
  // 为数据点添加位置信息
  const enhancedData = chartData.lineData.map((item) => {
    return {
      ...item,
      linkName: chartData.linkName || '',
      blockName: chartData.blockName || ''
    };
  });
  
  maxChartOptionData.value.series[lineType].data = enhancedData;
  maxChartOptionData.value.xAxis.data = xAxisData;
  
  const chartEl = document.getElementById("temperature0");
  if (chartEl) {
    const chartInstance = echarts.init(chartEl);
    chartInstance.resize();
    chartInstance.clear();
    chartInstance.setOption(maxChartOptionData.value);
    maxChartSetup.value = true;
  }
};
const minChartSetup = ref(false);
const initMinChart = async (chartData, lineType) => {
  // 1-最低温度 2-最高温度
  const xAxisData = chartData.lineData.map(
    (item) => item.dateTime.split(" ")[1]
  );
  
  // 构建tooltip数据
  buildTooltipData(chartData, minTooltipData);
  
  // 为数据点添加位置信息
  const enhancedData = chartData.lineData.map((item) => {
    return {
      ...item,
      linkName: chartData.linkName || '',
      blockName: chartData.blockName || ''
    };
  });
  
  minChartOptionData.value.series[lineType].data = enhancedData;
  minChartOptionData.value.xAxis.data = xAxisData;
  
  const chartEl = document.getElementById("temperature1");
  if (chartEl) {
    const chartInstance = echarts.init(chartEl);
    chartInstance.setOption(minChartOptionData.value);
    minChartSetup.value = true;
  }
};
const allChartSetup = computed(
  () => maxChartSetup.value && minChartSetup.value
);
watch(
  () => allChartSetup.value,
  (val) => {
    if (val) {
      const groupedData = {};
      // 根据日期分组数据
      allChartsData.value
        .flat()
        .forEach(({ lineType, date, lineData, blockName, linkName }) => {
          if (!groupedData[date]) {
            groupedData[date] = {
              lineType1: null,
              lineType2: null,
              blockName: null,
              linkName: null,
              stationName: null,
            };
          }
          if (lineType === 1) {
            groupedData[date].lineType1 = lineData;
            groupedData[date].blockName = blockName || null;
            groupedData[date].linkName = linkName || null;
            groupedData[date].stationName = props.stationInfo.name || null;
          } else if (lineType === 2) {
            groupedData[date].lineType2 = lineData;
            groupedData[date].blockName = blockName || null;
            groupedData[date].linkName = linkName || null;
            groupedData[date].stationName = props.stationInfo.name || null;
          }
        });
      // 处理数据，计算温度差值
      const result = [];
      for (const date in groupedData) {
        const { lineType1, lineType2, linkName, blockName, stationName } =
          groupedData[date];
        if (lineType1 && lineType2) {
          const lineDataDiff = lineType2.map((item, index) => ({
            ...item,
            value: !!item.value
              ? Number((item.value - lineType1[index].value).toFixed(2))
              : null,
          }));
          result.push({
            date,
            linkName,
            blockName,
            stationName,
            lineData: lineDataDiff,
            lineType: 3,
          });
        }
      }
      result.forEach((chart, index) => {
        initDiffChart(chart, index);
      });
    }
  }
);
const initDiffChart = async (chartData, lineType) => {
  chartsTableData.value.push(chartData);
  // 温差 即 最高温度-最低温度
  const xAxisData = chartData.lineData.map(
    (item) => item.dateTime.split(" ")[1]
  );
  diffChartOptionData.value.series[lineType].data = chartData.lineData.map(
    (item) => {
      return {
        ...item,
        // value: random(0, 500),
      };
    }
  );
  diffChartOptionData.value.xAxis.data = xAxisData;
  const chartEl = document.getElementById("temperature2");
  if (chartEl) {
    const chartInstance = echarts.init(chartEl);
    chartInstance.setOption(diffChartOptionData.value);
  }
};
const getLineData = async (date, lineType) => {
  const params = {
    stationId: props.stationInfo.id,
    lineType, // 1-最低温度 2-最高温度
    dimensionType: chartType.value,
    date,
  };
  if (chartType.value === 1) {
    // 如果是电池簇
    params.componentId = form.value.equipId;
  } else if (chartType.value === 2) {
    // 如果是电池堆
    params.componentId = form.value.linkId;
  }
  const res = await $api.temperatureData(params);
  const tableData = res.data.map((item, index) => {
    item.stationName = props.stationInfo.name;
    /* if (item.lineData) {
      item.lineData = item.lineData.map((dataItem, dataIndex) => ({
        ...dataItem,
        isBuild: dataIndex < 5 ? true : undefined,
      }))
    } */
    return item;
  });
  chartsTableData.value.push(tableData);
  return res?.data;
};
const allChartsData = ref([]);
const getTempData = async () => {
  if (!form.value.date) {
    message.error("请选择日期");
    return;
  }
  if (!chartType.value) {
    message.error("请选择维度");
    return;
  }
  switch (chartType.value) {
    case 1:
      // 如果是电池簇
      if (!form.value.equipId) {
        message.error("请选择电池簇");
        return;
      }
    case 2:
      // 如果是电池堆
      if (!form.value.linkId) {
        message.error("请选择电池堆");
        return;
      }
  }
  maxChartSetup.value = false;
  minChartSetup.value = false;
  chartsData.value = [];
  allChartsData.value = [];
  chartsTableData.value = [];
  const lineType = [1, 2]; // 1-最低温度 2-最高温度
  const dateList = [form.value.date, getYesterdayFromDate(form.value.date)];
  
  // 清空之前的tooltip数据
  maxTooltipData.value = {};
  minTooltipData.value = {};
  
  maxChartOptionData.value = getTemperatureOption("max", chartType.value, maxTooltipData.value);
  minChartOptionData.value = getTemperatureOption("min", chartType.value, minTooltipData.value);
  diffChartOptionData.value = cloneDeep(diffOption);
  for (const item of lineType) {
    // 根据lineType循环获取对应的数据
    chartLoading.value = true;
    emit('loading-change', true);
    const promises = dateList.map((date) => getLineData(date, item));
    await Promise.all(promises).then((chartData) => {
      chartLoading.value = false;
      emit('loading-change', false);
      chartsData.value = chartData;
      allChartsData.value.push(...chartData);
      chartsTableData.value.push(...chartData);
      chartsData.value.flat().forEach((chart, index) => {
        if (item === 1) {
          initMinChart(chart, index);
        }
        if (item === 2) {
          initMaxChart(chart, index);
        }
      });
    });
  }
};
const handleChageStation = async () => {
  form.value.date = getCurrentDate();
  await getEnergyLinkList();
  // await getTempDimension();
};
const chartsTableData = ref([]);
// 外部参数监听
watch(() => props.externalParams, (newParams) => {
  if (newParams && Object.keys(newParams).length > 0) {
    // 同步外部参数到内部状态
    if (newParams.chartType !== undefined) {
      chartType.value = newParams.chartType;
    }
    if (newParams.date) {
      form.value.date = newParams.date;
    }
    if (newParams.linkId !== undefined) {
      form.value.linkId = newParams.linkId;
    }
    if (newParams.equipId !== undefined) {
      form.value.equipId = newParams.equipId;
    }
    if (newParams.energyLinkList) {
      energyLinkList.value = newParams.energyLinkList;
    }
    if (newParams.blockList) {
      blockList.value = newParams.blockList;
    }
  }
}, { deep: true, immediate: true });
defineExpose({ 
  handleChageStation,
  getTempData,
  changeChartType,
  form,
  chartType
});
</script>

<style lang="less" scoped>
.chartForm {
  margin-top: 20px;
}
.ant-form-item {
  margin-bottom: 20px;
}
.chartContainer {
  margin-bottom: 20px;
  width: 100%;
  height: 370px;
  background: #141414;
  border-radius: 4px;
}
.chartContent {
 
}
.formInput {
  width: 180px;
}
.filterBtn {
  margin-right: 20px;
}
</style>
